import 'package:fluro/fluro.dart';
import 'package:flutter/material.dart';
import 'package:flutter_easyrefresh/easy_refresh.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:flutter_spinkit/flutter_spinkit.dart';
import 'package:flutter_swiper/flutter_swiper.dart';
import 'package:jtsell_app/provider/index_page_model.dart';
import 'package:jtsell_app/provider/main_category_model.dart';
import 'package:jtsell_app/provider/mall_goods_model.dart';
import 'package:jtsell_app/routes/routes.dart';
import 'package:provider/provider.dart';

import '../config/app_config.dart';
import '../entity/category_entity.dart';
import '../entity/mall_goods_entity.dart';
import '../entity/slide_entity.dart';
import '../network/http_dispense.dart';
import 'detail/goods_detail_page.dart';

class HomePage extends StatefulWidget {
  @override
  _HomePageState createState() => _HomePageState();
}

class _HomePageState extends State<HomePage> with AutomaticKeepAliveClientMixin {
  int currentPageIndex = 1;

  GlobalKey<RefreshHeaderState> _headerKey = new GlobalKey<RefreshHeaderState>();
  GlobalKey<RefreshFooterState> _footerKey = new GlobalKey<RefreshFooterState>();

  ///热门信息提示
  Widget _hotTitle() {
    ///检测状态
    if (mounted) {}

    return Container(
        margin: EdgeInsets.only(top: 10.0),
        padding: EdgeInsets.all(5.0),
        alignment: Alignment.center,
        decoration: BoxDecoration(
            color: Colors.white,
            border: Border(bottom: BorderSide(width: 0.5, color: Colors.black12))),
        child: Text('火爆专区'));
  }

  ///
  /// 下拉加载更多
  ///
  Future _loadMoreHandler() {
    return HttpDispense.getMallGoodsList({"page": currentPageIndex}).then((newList) {
      mallGoodsModel.streamCtrl.sink.add(newList);
      currentPageIndex++;
      return;
    }).catchError((error) {
      print(error);

      return;
    });
  }

  @override
  bool get wantKeepAlive => true;

  @override
  void initState() {
    // TODO: implement initState
    super.initState();

    _loadMoreHandler();
  }

  @override
  Widget build(BuildContext context) {
    super.build(context);

    return Scaffold(
      appBar: AppBar(
        title: Text("首页"),
      ),
      body: EasyRefresh(
          autoLoad: true,
          loadMore: _loadMoreHandler,
          refreshFooter: ClassicsFooter(
            key: _footerKey,
            loadHeight: ScreenUtil().setHeight(150),
            showMore: true,
            noMoreText: '加载完成',
            moreInfo: '加载中',
            loadReadyText: '上拉加载....',
            loadingText: "加载中",
            loadedText: "加载完成",
            loadText: "上拉加载",
            bgColor: Theme.of(context).primaryColor,
          ),
          child: ListView(
            children: <Widget>[
              SlidesWidget(),
              CategoryWidget(),
              _hotTitle(),
              MallGoodsWrap(),
            ],
          )),
    );
  }
}

///
/// 首页轮播
///
class SlidesWidget extends StatelessWidget {
  final Future<SlideEntity> _slidesFuture = HttpDispense.getSlidesContent();

  @override
  Widget build(BuildContext context) {
    return Container(
      height: ScreenUtil.getInstance().setHeight(350),
      child: FutureBuilder<SlideEntity>(
        future: _slidesFuture,
        builder: (BuildContext context, AsyncSnapshot<SlideEntity> snapshot) {
          return Swiper(
            itemBuilder: (BuildContext context, int index) {
              String imageUrl = "";
              if (!snapshot.hasError) {
                SlideEntity slideEntity = snapshot.data;
                if (slideEntity != null && slideEntity.slides.length > index) {
                  imageUrl = slideEntity.slides[index].image;
                }
              }

//              return CachedNetworkImage(
//                imageUrl: imageUrl,
//                placeholder: (context, url) => new LinearProgressIndicator(),
//                errorWidget: (context, url, error) => new Icon(Icons.error),
//                fit: BoxFit.cover,
//              );

              return Image.network(imageUrl);
            },
            autoplay: true,
            loop: true,
            itemCount: 3,
            scale: 0.95,
            viewportFraction: 0.85,
            pagination: new SwiperPagination(margin: const EdgeInsets.all(0)),
          );
        },
      ),
    );
  }
}

///
/// 首页分类
///
class CategoryWidget extends StatelessWidget {
  final Future<List<CategoryEntity>> _categoryEntityFuture = HttpDispense.getCategoryList();

  ///loading加载框
  Widget _loadingView() {
    return LimitedBox(
      maxHeight: ScreenUtil().setHeight(430),
      child: SpinKitWave(
        size: ScreenUtil().setHeight(80),
        type: SpinKitWaveType.center,
        itemBuilder: (BuildContext context, int index) {
          return DecoratedBox(
              decoration: BoxDecoration(
            color: index.isEven ? Colors.red : Colors.yellow,
          ));
        },
      ),
    );
  }

  ///
  /// 获取分类列表
  ///
  List<Widget> _getList(BuildContext context, List<CategoryEntity> entitys) {
    int categoryIndex = 0;

    return entitys.map((item) {
      ///存储当前实例化对象的索引值
      int index = categoryIndex++;

      return InkWell(
        onTap: () {
          ///切换分类列表的索引
          Provider.of<MainCategoryModel>(context).setCurrentIndex(index);

          ///导航到分类页
          Provider.of<IndexPageModel>(context)
              .setCurrentPageIndex(IndexPageModel.CATEGORY_PAGE_INDEX);
        },
        child: Column(
          children: <Widget>[
            Image.network(item.image, width: ScreenUtil().setWidth(150)),
            Text(
              item.mallCategoryName,
              style: TextStyle(fontSize: ScreenUtil().setSp(35)),
            ),
          ],
        ),
      );
    }).toList();
  }

  @override
  Widget build(BuildContext context) {
    return Card(
        child: FutureBuilder<List<CategoryEntity>>(
            future: _categoryEntityFuture,
            builder: (BuildContext context, AsyncSnapshot snapshot) {
              if (snapshot.connectionState != ConnectionState.done) {
                return _loadingView();
              }

              if (snapshot.hasError) {
                return _loadingView();
              }

              List<CategoryEntity> entitys = snapshot.data;
              if (entitys == null || entitys.isEmpty) {
                print(entitys);
                return _loadingView();
              }

              if (entitys.length > 10) {
                entitys.removeRange(10, entitys.length);
              }

              return Container(
                color: Colors.white,
                margin: EdgeInsets.only(top: 5.0),
                height: ScreenUtil().setHeight(420),
                padding: EdgeInsets.all(3.0),
                child: GridView.count(
                  physics: NeverScrollableScrollPhysics(),
                  crossAxisCount: 5,
                  padding: EdgeInsets.all(4.0),
                  children: _getList(context, entitys),
                ),
              );
            }));
  }
}

///
/// 热门项目的Wrap
///
class MallGoodsWrap extends StatelessWidget {
  final List<MallGoodsEntity> mallGoodsList = List();
  BuildContext _context;

  ///
  ///热门商品项目
  ///
  Widget _mallGoodsItem(MallGoodsEntity mallGoods) {
    const double WIDGET_WIDTH = AppConfig.SCREEN_WIDTH / 2 - 20;
    return InkWell(
        onTap: () {
          ///跳转到详情页
          Routes.getInstance().pushGoodsDetailPage(_context, mallGoods.goodsId);
        },
        child: Container(
          width: ScreenUtil().setWidth(WIDGET_WIDTH),
          padding: EdgeInsets.all(ScreenUtil().setWidth(20)),
          margin: EdgeInsets.all(ScreenUtil().setWidth(4)),
          decoration: BoxDecoration(
              color: Colors.white,
              border: Border(left: BorderSide(width: 0.5, color: Colors.black12))),
          child: Column(
            mainAxisAlignment: MainAxisAlignment.center,
            children: <Widget>[
              ///商品图片
              Hero(
                  tag: '${mallGoods.goodsId}',
                  child: Image.network(
                    mallGoods.image,
                    fit: BoxFit.cover,
                    width: ScreenUtil().setWidth(WIDGET_WIDTH),
                    height: ScreenUtil().setHeight(AppConfig.SCREEN_HEIGHT / 5.5),
                  )),
              SizedBox(
                width: ScreenUtil().setWidth(WIDGET_WIDTH),
                child: Text(
                  mallGoods.goodsName,
                  textAlign: TextAlign.left,
                  overflow: TextOverflow.ellipsis,
                  maxLines: 1,
                ),
              ),
              Row(
                children: <Widget>[
                  Text('￥${mallGoods.presentPrice}'),
                  Text('￥${mallGoods.oriPrice}',
                      style:
                          TextStyle(color: Colors.black26, decoration: TextDecoration.lineThrough)),
                ],
              )
            ],
          ),
        ));
  }

  ///将热门商品转换成组件
  List<Widget> _getMallGoodsWidgetList(List<MallGoodsEntity> newList) {
    if (newList != null && newList.isNotEmpty) {
      mallGoodsList.addAll(newList);
    }

    List<Widget> mallGoodsWidgetList = List();

    if (mallGoodsList == null || mallGoodsList.isEmpty) {
      mallGoodsWidgetList.add(Text("暂无数据"));
    } else {
      return mallGoodsList.map(_mallGoodsItem).toList();
    }

    return mallGoodsWidgetList;
  }

  @override
  Widget build(BuildContext context) {
    _context = context;

    return StreamProvider<List<MallGoodsEntity>>.controller(
      builder: (BuildContext context) => mallGoodsModel.streamCtrl,
      catchError: (BuildContext context, Object error) {
        print("------->$error");
      },
      child: Consumer<List<MallGoodsEntity>>(
          builder: (BuildContext context, List<MallGoodsEntity> mallGoodList, Widget child) {
        return Wrap(
          spacing: 2,
          children: _getMallGoodsWidgetList(mallGoodList),
        );
      }),
    );
  }
}
